/**
 * Created with JetBrains PhpStorm.
 * User: ueaner
 * Date: 7/10/13
 * Time: 3:36 PM
 * To change this template use File | Settings | File Templates.
 */

/**
 * 文件上传
 *
 * @param uploadBtn 点击触发上传事件的元素ID
 * @param uploadFile 要上传的文件元素ID
 * @param callback 回调函数
 * @param uploadUrl 文件上传地址（可为空）
 */
function uploadFile(uploadBtn, uploadFile, callback, uploadUrl) {
    if (typeof callback != "function") {
        callback = function() {};
    }
    $("#"+uploadBtn).click(function() {
        var data = new FormData();
        data.append('file', $("#"+uploadFile)[0].files[0]);

        $.ajax({
            url: uploadUrl ? uploadUrl : '/file/upload',
            data: data,
            cache: false,
            contentType: false,
            processData: false,
            dataType: "jsonp",
            type: 'POST',
            success: callback
        });
    })
}

function isIE() {
    return /*@cc_on!@*/false;
}

/**
 * 百度编辑器
 * 使用：
 * 首先定义基础信息：
 * window.UEDITOR_HOME_URL = 'http://'+document.domain+'/static/js/ueditor/'; // UEditor 根目录
 * window.FILE_SERVER = "{$smarty.const.FILE_SERVER}"; // 文件上传服务地址
 *
 * 引入 UEditor 相关文件，会用到以上变量信息
 * <script src="{staticurl action="ueditor/ueditor.config.js"}" charset="utf-8"></script>
 * <script src="{staticurl action="ueditor/ueditor.all.min.js"}" charset="utf-8"></script>
 *
 * 引入本文件
 * <script src="{staticurl action="common/utils.js"}"></script>
 *
 * 初始化编辑器
 * Editor.init([container]);
 */
var Editor = {
    init: function (container, imageUrl, imagePath, remoteImageUrl, getMovieUrl) {
        //实例化编辑器
        var options = {
            imageUrl: imageUrl == undefined ? window.FILE_SERVER+"?module=mgr&sort=editor" : imageUrl,
            imagePath: imagePath == undefined ? '' : imagePath,
            catcherUrl: remoteImageUrl == undefined ? "http://"+document.domain+"/file/getremoteimage" : remoteImageUrl,
            catcherPath: imagePath == undefined ? window.FILE_SERVER : imagePath,
            getMovieUrl: getMovieUrl == undefined ? "http://"+document.domain+"/file/getmovie" : getMovieUrl,

            toolbars: [
                ['fullscreen', 'source', '|', 'undo', 'redo', '|',
                    'bold', 'italic', 'underline', 'fontborder', 'strikethrough', 'superscript', 'subscript', 'removeformat', 'formatmatch', 'autotypeset', 'blockquote', 'pasteplain', '|', 'forecolor', 'backcolor', 'insertorderedlist', 'insertunorderedlist', 'selectall', 'cleardoc', '|',
                    'rowspacingtop', 'rowspacingbottom', 'lineheight', '|',
                    'customstyle', 'paragraph', 'fontfamily', 'fontsize', '|',
                    'directionalityltr', 'directionalityrtl', 'indent', '|',
                    'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|', 'touppercase', 'tolowercase', '|',
                    'link', 'unlink', 'anchor', '|', 'imagenone', 'imageleft', 'imageright', 'imagecenter', '|',
                    'insertimage', 'emotion', 'insertvideo', 'music', 'map', 'gmap', 'insertframe', 'insertcode', 'pagebreak', 'template', '|',
                    'horizontal', 'date', 'time', 'spechars', 'wordimage', '|',
                    'inserttable', 'deletetable', 'insertparagraphbeforetable', 'insertrow', 'deleterow', 'insertcol', 'deletecol', 'mergecells', 'mergeright', 'mergedown', 'splittocells', 'splittorows', 'splittocols', '|',
                    'print', 'preview', 'searchreplace', 'help']
            ],
            initialFrameWidth: 840,
            initialFrameHeight: 420,
            focus: false
        };
        var editorElem = typeof container == 'undefined' ? 'editor' : container;
        var ue = UE.getEditor(editorElem, options);
//        var domUtils = UE.dom.domUtils;
//        ue.addListener("ready", function () {
//        ue.focus(true);
//        });
    },

    hasContents: function () {
        return UE.getEditor('editor').hasContents();
    }
};

var tips = {
    'province': '省',
    'city': '市',
    'district': '区',
    'settlement' : '结算方式',
    'supplier_contract_bank_id' : '供应商账户',
    'company_bank_id' : '公司账户',
    'type' : '性质'

};

/**
 * 表单提交具有 require="require" 的元素为必填项
 * 注意：为确保 value="0" 的数据为必填项也可提交（如性别男为0），
 *      请写成 value=""
 */
function required() {
    var flag = true,
        value = '',
        tip,
        require,
        id;
    $("*[require]").each(function(i) {
        value = $.trim($(this).val());
        id = $(this).attr("id");
        tip = $.trim($(this).parent().prev().text()).replace(/\*$/,'');
        require = $(this).attr('require');
        if (value == '') {
            if (i == 0) {
                $(this).focus();
            }
            if ($(this).get(0).tagName == "SELECT") {
                tip = '请选择：' + tips[id];
            } else {
                tip += ": 不能为空";
            }
            alert(tip);
            // each 的 function 参数只能使用 return false 退出
            flag = false;
            return false;
        }
        if (require != 'require' && require != '' && regex[require] && !regex[require].test(value)) {
            alert(tip + ": 格式不正确");
            flag = false;
            return false;
        }
        $(this).val(value);
    });
    return flag;
}

/**
 * 截取字符串 包含中文处理
 *
 * @param str
 * @param len
 * @param hasDot
 * @returns {string}
 * @author ueaner
 */
function subString(str, len, hasDot) {
    var newLength = 0;
    var newStr = "";
    var chineseRegex = /[^\x00-\xff]/g;
    var singleChar = "";
    var strLength = str.replace(chineseRegex, "**").length;
    for(var i = 0;i < strLength; i++) {
        singleChar = str.charAt(i).toString();
        if (singleChar.match(chineseRegex) != null) {
            newLength += 2;
        } else {
            newLength++;
        }
        if(newLength > len) {
            break;
        }
        newStr += singleChar;
    }

    if(hasDot && strLength > len) {
        newStr += "...";
    }
    return newStr;
}

/**
 * 单图上传
 */
function singleImageUpload(data) {
    if (typeof data.status != 'undefined' && data.status == 200) {
        $("#thumb-field").val(data.msg.server_name);
        var img = "<img src='" + data.msg.url + "' type=3>"
        $("#thumb-preview").html(img);
    } else {
        $("#thumb-preview").html(data.msg);
    }
}

//多个上传-合同上传

function moreImageUpload(data, i) {
	i++;
    if (typeof data.status != 'undefined' && data.status == 200) {
        var append = '<div style="width: 230px">';
            // 查看上传文件链接
            append += "<a target='_blank' href='" + data.msg.url + "' title='"+data.msg.original_name+"'>" + subString(data.msg.original_name, 24, true) + "</a>";
            // 记录上传文件ID
            append += "<input type='hidden' id='' name='project_contract_file["+i+"]' value='"+data.msg.server_name+"' />";
            // 删除文件链接
            append += "<a class='right' href='javascript:void(0);' onclick='deleteFile(this);'>删除</a>";
            append +='</div>';
        $("#thumb-preview").append(append);
        $("#uploadPreviewMsg").html("");
    } else {
        $("#uploadPreviewMsg").html(data.msg);
    }
}

var regex = {
    mobile: /^1[0-9]{10}$/,
    phone: /^(\d{3,5}-\d{7,8}|\d{4}-\d{7})(-(\d{3,5}))?$/,
    email: /^(\w)+(\.\w+)*@(\w)+((\.\w+)+)$/,
	username:/^[a-z|A-Z]\w{3,15}$/,
	password:/^(([a-z|A-Z|0-9])|(\.)|(\_)){6,16}$/,
	zip:/^[0-9]{6}$/,
	area:/^[0-9]{3,6}$/,
	only_phone:/^[0-9]{7,8}$/,
	number_code:/^[0-9]{6}$/,
	code:/^[0-9|A-Z|a-z]{6}$/,
    price: /^(\d+)(\.?)(\d{0,2})$/
};
// regex.test(phone)

/**
 * 比较两个日期或时间的大小
 * @param startTime
 * @param endTime
 * @returns {boolean}
 * @author ueaner
 */
function compareDate(startTime, endTime) {
    var startDate = new Date(startTime.replace(/-/g, "/")),
        endDate = new Date(endTime.replace(/-/g, "/"));
    return Date.parse(endDate) - Date.parse(startDate) >= 0;
}

/**
 * 检查input表单输入的金额值数据格式
 * @param object inputObj
 * @author zy
 * 
 */
function checkInputPrice(inputObj) {
	var inputObject = $(inputObj);
	var inputId = $(inputObj).attr('id');
	var val = $("#"+inputId).val();
	
	var hiddenPrefix = 'hidden';
	// 临时保存对象不存在则创建
	var hiddenInputObject = $("#hidden_"+inputId).val();
	if(typeof(hiddenInputObject) === 'undefined') {
		var init_value = $(inputObj).attr('init_value');
		if(typeof(init_value) === 'undefined') {
			init_value = '';
		}
		
		var hiddenInputObject = $('<input type="hidden" id="'+hiddenPrefix+'_'+inputId+'"  value="'+init_value+'" />');
		inputObject.after(hiddenInputObject);
	}
		
	if(val != '') {
		if(val.match(regex.price)) {
			// 满足价格格式，保存到临时存数。
			$("#"+hiddenPrefix+"_"+inputId).val(val);
			return true;
		}else {
			// 不满足价格格式，恢复之前的上一次的，正确的，存数
			var reVal = $("#"+hiddenPrefix+"_"+inputId).val();
			$("#"+inputId).val(reVal);
			return false;
		}
	}
	
	return false;
}